﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Demo.OrderManager.Orders.Dto;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Demo.OrderManager.Orders;

/// <summary>
/// 订单应用服务
/// </summary>
public class OrderAppService:ApplicationService,IOrderAppService
{
    private IRepository<Order,Guid> _orderRepository;
    
    public OrderAppService(IRepository<Order,Guid> orderRepository)
    {
        _orderRepository = orderRepository;
    }
    
    /// <summary>
    /// 创建订单
    /// </summary>
    /// <param name="input">订单对象</param>
    /// <returns></returns>
    public async Task<OrderDto> CreateAsync(OrderCreateDto input)
    {
        var order=new Order(GuidGenerator.Create(),input.ReferenceNo);
        
        foreach (var product in input.Products)
        {
            order.AddProduct(product.ProductId,product.Count);
        }
        var ret = await _orderRepository.InsertAsync(order);
        return ObjectMapper.Map<Order, OrderDto>(order);
    }

    /// <summary>
    /// 删除订单
    /// </summary>
    /// <param name="orderId">订单编号</param>
    /// <returns></returns>
    public async Task<bool> DeleteAsync(Guid orderId)
    {
        await _orderRepository.DeleteAsync(x => x.Id == orderId);
        return true;
    }

    /// <summary>
    /// 分页获取订单列表
    /// </summary>
    /// <param name="input">分页条件</param>
    /// <returns></returns>
    public async Task<PagedResultDto<OrderDto>> GetListAsync(PagedAndSortedResultRequestDto input)
    {
        var totalCount = await _orderRepository.GetCountAsync();
        var orders = await _orderRepository.GetPagedListAsync(input.SkipCount, input.MaxResultCount,
            input.Sorting ?? "CreationTime desc", true);
        var result = ObjectMapper.Map<List<Order>, List<OrderDto>>(orders);
        return new PagedResultDto<OrderDto>(
            totalCount,
            result
        );
    }

    /// <summary>
    /// 依据订单编号获取订单详情
    /// </summary>
    /// <param name="id">订单编号</param>
    /// <returns></returns>
    public async Task<OrderDetailDto> GetAsync(Guid id)
    {
        var order = await _orderRepository.GetAsync(x => x.Id == id, includeDetails: false);
        await _orderRepository.EnsureCollectionLoadedAsync(order, x => x.OrderLines);
        return ObjectMapper.Map<Order, OrderDetailDto>(order);
    }
}